<?php

namespace app\model\customer;

use think\Model;
use think\model\concern\SoftDelete;

/**
 * 客户附件模型
 * 用于管理客户相关的附件文件
 */
class CustomerFile extends Model
{
    // 使用软删除
    use SoftDelete;

    // 设置表名
    protected $name = 'customer_file';

    // 设置主键
    protected $pk = 'id';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    // 时间戳字段名称
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = 'delete_time';

    // 类型转换
    protected $type = [
        'id' => 'integer',
        'customer_id' => 'integer',
        'file_id' => 'integer',
        'create_time' => 'int',
        'update_time' => 'int',
        'delete_time' => 'int',
    ];

    /**
     * 获取客户的附件列表
     * 
     * @param int $customerId 客户ID
     * @return array 附件信息列表
     */
    public static function getCustomerFiles(int $customerId): array
    {
        return self::alias('cf')
            ->join('file f', 'cf.file_id = f.id', 'LEFT')
            ->field('cf.id, f.filepath, f.name, f.filesize, f.fileext, f.create_time, f.admin_id')
            ->where(['cf.customer_id' => $customerId, 'cf.delete_time' => 0])
            ->select()
            ->toArray();
    }

    /**
     * 添加客户附件
     * 
     * @param int $customerId 客户ID
     * @param int $fileId 文件ID
     * @param int $adminId 管理员ID
     * @return int|false 新记录ID或false
     */
    public static function addCustomerFile(int $customerId, int $fileId, int $adminId)
    {
        $customerFile = new self();
        $customerFile->customer_id = $customerId;
        $customerFile->file_id = $fileId;
        $customerFile->admin_id = $adminId;
        $customerFile->create_time = time();
        $customerFile->update_time = time();
        $customerFile->delete_time = 0;

        return $customerFile->save() ? $customerFile->id : false;
    }

    /**
     * 删除客户附件（软删除）
     * 
     * @param int $id 客户附件记录ID
     * @return bool 删除结果
     */
    public static function deleteCustomerFile(int $id): bool
    {
        return self::where(['id' => $id, 'delete_time' => 0])
            ->update(['delete_time' => time()]) !== false;
    }

    /**
     * 根据文件ID删除客户附件
     * 
     * @param int $customerId 客户ID
     * @param int $fileId 文件ID
     * @return bool 删除结果
     */
    public static function deleteCustomerFileByFileId(int $customerId, int $fileId): bool
    {
        return self::where([
            'customer_id' => $customerId,
            'file_id' => $fileId,
            'delete_time' => 0
        ])->update(['delete_time' => time()]) !== false;
    }

    /**
     * 获取客户的文件ID列表
     * 
     * @param int $customerId 客户ID
     * @return array 文件ID列表
     */
    public static function getCustomerFileIds(int $customerId): array
    {
        $files = self::where(['customer_id' => $customerId, 'delete_time' => 0])
            ->field('file_id')
            ->select()
            ->toArray();

        return array_column($files, 'file_id');
    }
}